package com.xinbochuang.machine.admin.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinbochuang.machine.admin.domain.*;
import com.xinbochuang.machine.admin.domain.macRoom.*;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.dto.MacInOutDto;
import com.xinbochuang.machine.admin.mapper.PowerOrderRoomMapper;
import com.xinbochuang.machine.admin.mapper.macRoom.*;
import com.xinbochuang.machine.admin.service.*;
import com.xinbochuang.machine.admin.service.macRoom.IEquCabinetService;
import com.xinbochuang.machine.admin.service.macRoom.IMacRoomService;
import com.xinbochuang.machine.admin.service.macRoom.IMacShowService;
import com.xinbochuang.machine.admin.service.macRoom.IUlocationService;
import com.xinbochuang.machine.admin.service.system.ISysUserService;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.domain.LoginUser;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.redis.RedisCache;
import com.xinbochuang.machine.common.utils.StringUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import com.xinbochuang.machine.framework.web.service.SysLoginService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 机房接入工单信息接口
 *
 * @author 马春刚
 * @date 2024-01-29 15:51
 */
@Api(value = "机房接入工单信息", position = 100, protocols = "http")
@RestController
@Validated
@RequestMapping("/jfjr")
public class PowerOrderApiController extends BaseController {
    @Resource
    private RedisCache redisCache;
    @Autowired
    IPowerOrderService powerOrderService;
    @Autowired
    IPowerOrderRoomService powerOrderRoomService;
    @Autowired
    IPowerOrderRackService powerOrderRackService;
    @Autowired
    MacBuildMapper macBuildMapper;
    @Autowired
    MacIndustrialMapper macIndustrialMapper;
    @Autowired
    MacRoomMapper macRoomMapper;
    @Autowired
    EquCabinetMapper equCabinetMapper;

    @Resource
    private ISysUserService iSysUserService;

    @Autowired
    PowerOrderRoomMapper powerOrderRoomMapper;
    /**
     *
     * 接受eoms推送过来的动力调度工单信息，并固化数据库
     * @return
     */
    @PostMapping("/addResPowerData")
    public AjaxResult addResPowerData(@RequestParam("data") String data){
        //String data= "[{\"orderCode\":\"ID-TSK-20240129-00018\",\"orderTitle\":\"关于进入西夏二枢纽221机房及502机房的申请\",\"createBy\":\"张龙\",\"createTime\":\"2024-01-29 11:14:56\", \"timeOut\":\"2024-01-30 11:14:56\",\"operate\":\"上电\",\"roomNames\":[\"银川市灵武区第二中学(专线)机房A01\",\"银川市灵武区第二中学(专线)机房A01\",\"银川市灵武区第二中学(专线)机房A01\"],\"rackNames\":[\"银川市灵武区第二中学(专线)机房A01设备机架-A01\",\"银川市灵武区第二中学(专线)机房A01\",\"银川市灵武区第二中学(专线)机房A01设备机架-A02\"],}]";
        JSONArray objects = JSONUtil.parseArray(data);
        for(int i=0;i<objects.size();i++){
            JSONObject jsonObject = objects.getJSONObject(i);
            PowerOrder PowerOrder=JSONUtil.toBean(jsonObject,PowerOrder.class);
            UUID uuid = UUID.randomUUID();
            PowerOrder.setId(uuid.toString());
            String rooms = jsonObject.getStr("roomNames");
            JSONArray arrRooms = JSONUtil.parseArray(rooms);
            Map<String,String> macRoomIdMap=new HashMap<>();
            for(int j=0;j<arrRooms.size();j++){
                Object joRoom = arrRooms.get(j);
                PowerOrderRoom powerOrderRoom= new PowerOrderRoom();
                powerOrderRoom.setId(UUID.randomUUID().toString());
                powerOrderRoom.setMacRoomName(joRoom.toString());
                powerOrderRoom.setMacPowerOrderId(uuid.toString());
                powerOrderRoom.setOrderCode(PowerOrder.getOrderCode());
                powerOrderRoom.setState("0");
                initRoomId(powerOrderRoom.getMacRoomName(),powerOrderRoom);
                if(StringUtils.isNotBlank(powerOrderRoom.getMacRoomId())){
                    macRoomIdMap.put(powerOrderRoom.getMacRoomName(),powerOrderRoom.getMacRoomId());
                }
                powerOrderRoomService.saveOrUpdate(powerOrderRoom);

            }
            String racks = jsonObject.getStr("rackNames");
            JSONArray arrRacks = JSONUtil.parseArray(racks);
            Map<String,List<EquCabinet>> equListMap=new HashMap<>();
            for(int k=0;k<arrRacks.size();k++){
                Object joRack = arrRacks.get(k);
                //JSONObject joRack= arrRacks.getJSONObject(k);
                PowerOrderRack powerOrderRack=new PowerOrderRack();
                powerOrderRack.setId(UUID.randomUUID().toString());
                powerOrderRack.setMacRackName(joRack.toString());
                powerOrderRack.setMacPowerOrderId(uuid.toString());
                powerOrderRack.setOrderCode(PowerOrder.getOrderCode());
                powerOrderRack.setState("0");
                initRockId(powerOrderRack,macRoomIdMap,equListMap);
                powerOrderRackService.saveOrUpdate(powerOrderRack);
            }
            powerOrderService.saveOrUpdate(PowerOrder);
        }
        return AjaxResult.ok();
    }

    private void initRockId(PowerOrderRack powerOrderRack, Map<String, String> macRoomIdMap,Map<String,List<EquCabinet>> equListMap) {
        String macRackName = powerOrderRack.getMacRackName();
        for(String name:macRoomIdMap.keySet()){
            String roomId = macRoomIdMap.get(name);
            List<EquCabinet> equCabinets=new ArrayList<>();
            if(equListMap.containsKey(roomId)){
                equCabinets=equListMap.get(roomId);
            }
            LambdaQueryWrapper<EquCabinet> equipmentLambdaQueryWrapper=new LambdaQueryWrapper<>();
            equipmentLambdaQueryWrapper.eq(EquCabinet::getMacId, macRoomIdMap.get(name));
            equCabinets=equCabinetMapper.selectList(equipmentLambdaQueryWrapper);
            for(EquCabinet cabinet:equCabinets){
                if(macRackName.contains(cabinet.getCabinetName())){
                    powerOrderRack.setMacRockId(cabinet.getUuid());
                }
            }
        }
    }

    public void initRoomId(String name,PowerOrderRoom powerOrderRoom){
        String id=redisCache.getCacheObject("roomname_"+name);
        if(StringUtils.isNotBlank(id)){
            powerOrderRoom.setMacRoomId(id);
            return;
        }
        Integer integer = macIndustrialMapper.selectCount(new LambdaQueryWrapper<>());
        Integer industrial_length = redisCache.getCacheObject("Industrial_length");
        if(industrial_length==null){
            industrial_length=0;
        }
        List<MacIndustrial> macIndustrials=new ArrayList<>();
        if(industrial_length<integer){
            macIndustrials = macIndustrialMapper.selectList(new LambdaQueryWrapper<>());
            redisCache.setCacheList("Industrial_List",macIndustrials);
        }else{
            redisCache.getCacheList("Industrial_List");
        }
        for(MacIndustrial macIndustrial:macIndustrials){
            if(name.contains(macIndustrial.getName())){
                String industrialId = macIndustrial.getId();
                LambdaQueryWrapper<MacBuild> macBuildLambdaQueryWrapper=new LambdaQueryWrapper<>();
                macBuildLambdaQueryWrapper.eq(MacBuild::getIndustrialId,industrialId);
                List<MacBuild> macBuilds = macBuildMapper.selectList(macBuildLambdaQueryWrapper);
                for(MacBuild macBuild:macBuilds){
                    if(name.contains(macBuild.getName())){
                        String macBuildId = macBuild.getId();
                        LambdaQueryWrapper<MacRoom> roomLambdaQueryWrapper=new LambdaQueryWrapper<>();
                        roomLambdaQueryWrapper.eq(MacRoom::getBuildId,macBuildId);
                        List<MacRoom> macRooms = macRoomMapper.selectList(roomLambdaQueryWrapper);
                        for(MacRoom macRoom:macRooms){
                            if(name.contains(macRoom.getMacName())){
                                powerOrderRoom.setMacRoomId(macRoom.getUuid());
                                redisCache.setCacheObject("roomname_"+name,macRoom.getUuid());
                            }
                        }
                    }
                }
            }
        }
    }


    @GetMapping("/getMessageNum")
    public AjaxResult getMessageNum(@RequestParam("username") String username) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUsername,username);
        List<SysUser> list = iSysUserService.list(sysUserLambdaQueryWrapper);
        if(list.isEmpty()){
            return AjaxResult.data(0);
        }
        String nickname = list.get(0).getNickname();
        LambdaQueryWrapper<PowerOrderRoom> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.inSql(PowerOrderRoom::getMacRoomId,"select uuid from mac_room where update_by='"+nickname+"'").eq(PowerOrderRoom::getState,"0");
        Integer integer = powerOrderRoomMapper.selectCount(lambdaQueryWrapper);
        return AjaxResult.data(integer);
    }
}
